import configparser
import datetime
import time
import traceback

import api as api
import get_image
from DBAction import DBAction
from member import Member


def get_member_all_images(id):
    """
    获取成员全部图片
    """
    url = 'https://pocketapi.48.cn/posts/api/v1/posts/img/list'
    params = {
        "nextId": 0,
        "userId": id
    }
    response = api.post(url, params)
    if response['status'] == 200:
        print(response)


def config_day_plus_one():
    # 自动修改config
    #  实例化configParser对象
    config = configparser.ConfigParser()
    # -read读取ini文件
    config.read(r'./config/config.ini', encoding='GB18030')
    start_time = config.get('member', 'start_time')

    config.set('member', 'end_time', start_time)

    newstart = datetime.datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S") + datetime.timedelta(days=1)
    config.set('member', 'start_time', newstart.strftime("%Y-%m-%d %H:%M:%S"))
    # 保存修改
    with open(r'./config/config.ini', "w") as fw:
        config.write(fw)  # 使用write将修改内容写到文件中，替换原来config文件中内容


# 记得修改sql语句和在member循环中执行的操作
if __name__ == '__main__':
    # config_day_plus_one()
    # TODO 在这里凌晨三点开始
    time.sleep(3600 * 3)

    print(time.time())
    api.start_schedule()
    db = DBAction('pocket48')
    #  按照粉丝数获得member_list
    #  实例化configParser对象
    config = configparser.ConfigParser()
    # -read读取ini文件
    config.read(r'./config/config.ini', encoding='GB18030')
    startfannum = config.getint('member', 'startFanNum')

    result = db.data_inquiry_all("SELECT m.memberid,r.roomid FROM member m left join room r on m.memberid=r.memberid "
                                 f"where m.fan_num < {startfannum} and r.roomid is not null order by m.fan_num desc")
    member_list = []
    for data in result:
        member_list.append(Member(data[0], data[1]))
    print('total: ', len(member_list))
    start_time = config.get('member', 'start_time')
    end_time = config.get('member', 'end_time')
    print(start_time, end_time)
    # 对每个成员进行操作
    # 用index是因为可能中断
    index = 0
    while True:
        try:
            while index < len(member_list):
                member = member_list[index]
                print("curid:", member.id)
                # member.get_fanpai_price()
                # member.update_avatar_and_fannum()

                # 这三个是一块的
                member.get_msg_between(start_time, end_time)
                api.wait_random_time()
                index += 1
                print(time.time(), ' | progress: ', index / len(member_list))
            break
        except Exception as e:
            api.logger.info(traceback.format_exc())
            print(e.__str__())
            print(traceback.format_exc())
            api.wait_random_time(20)

    # 下载其中的资源
    get_image.get_roommsg_source(start_time, end_time)
    get_image.get_fanpai(start_time, end_time)
    print(time.time(), 'done')
